package org.dromara.common.tenant.handle

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler
import io.github.oshai.kotlinlogging.KotlinLogging
import net.sf.jsqlparser.expression.Expression
import net.sf.jsqlparser.expression.NullValue
import net.sf.jsqlparser.expression.StringValue
import org.dromara.common.core.utils.StringUtils
import org.dromara.common.tenant.helper.TenantHelper
import org.dromara.common.tenant.properties.TenantProperties

/**
 * 自定义租户处理器
 *
 * @author LikeYouDo
 * @date 2025/07/26
 */
class PlusTenantLineHandler(
    private val tenantProperties: TenantProperties,
): TenantLineHandler {

    companion object{
        private val log = KotlinLogging.logger {  }
    }
    override fun getTenantId(): Expression {
        val tenantId = TenantHelper.getTenantId()
        if (StringUtils.isBlank(tenantId)) {
            log.error { "无法获取有效的租户id -> Null" }
            return NullValue()
        }
        // 返回固定租户
        return StringValue(tenantId)
    }

    override fun ignoreTable(tableName: String): Boolean {
        val tenantId = TenantHelper.getTenantId()
        // 判断是否有租户
        if (StringUtils.isNotBlank(tenantId)) {
            // 不需要过滤租户的表
            val excludes = tenantProperties.excludes
            // 非业务表
            val tables: MutableList<String> = mutableListOf(
                "gen_table",
                "gen_table_column"
            )
            tables.addAll(excludes)
            return StringUtils.equalsAnyIgnoreCase(tableName, *tables.toTypedArray<String>())
        }
        return true
    }
}
